<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: ImportHelpPages.php 377 2010-09-10 08:14:28Z steen.rabol $
 *
 */

Prado::using('Application.Common.Data.PortalHelpRecord');

class ImportHelpPages extends PortalAdminPage
{
	private $_culture;

	public static function ToolMenuName()
	{
		return Prado::localize('Import help pages');
	}

	public function onLoad($param)
	{
		parent::onLoad($param);

		$this->PageTitle = "Import help pages";
		$this->FileUpload->setAttribute("size",30);

		if(!$this->IsPostBack)
		{
			$this->FileUpload->MaxFileSize	= PortalUtil::return_bytes(ini_get('upload_max_filesize'));
			$this->ltFileSize->Text			= ini_get('upload_max_filesize');
		}
	}

	public function onFileUpload($sender,$param)
	{
		if($sender->HasFile)
		{
			PortalUtil::CreateDirStructure($this->Application->PortalBasePath	. '/storage/tmp');

			$savepath	= $this->Application->PortalBasePath	. '/storage/tmp/' . $sender->FileName;
			$sender->saveAs($savepath);
			$langstrings	= $this->loadHelpFile($savepath);

			if(TPropertyValue::ensureInteger($this->DeleteFirst->Checked))
			{
				$sql = "delete from tblhelp where culture='" . $this->_culture . "'";
				try
				{
					$this->DbConnection->createCommand($sql)->execute();
				}
				catch(Exception $e)
				{
					$this->reportError(1,$e->getMessage());
				}
			}

			foreach($langstrings as $langstring)
			{
				$hp = PortalHelpRecord::finder()->findBypagename_AND_culture($langstring[1],$this->_culture);

				if(!$hp)
				{
					$hp = new PortalHelpRecord();
					$hp->culture	= $this->_culture;
					$hp->pagename	= $langstring[1];
				}

				$hp->content	= $langstring[3];
				$hp->title		= $langstring[2];
				$hp->save();
			}
		}
	}

	public function loadHelpFile($filename)
	{
		$XML = simplexml_load_file($filename);
		if(!$XML)
			return false;

		// Get culture from file
		foreach($XML as $h)
		{
			$a = $h->attributes();
			$this->_culture	= (string)$a->culture;
			break;
		}

		$translationStrings = $XML->xpath('//helppage');
		$translations = array();

		foreach($translationStrings as $string)
		{
			$attr = $string->attributes();
			$translations[] = array((string)$attr->id,(string)$string->pagename,(string)$string->title,(string)$string->content);
		}
		return $translations;
	}
}

?>